package dianmobile.eistarandroid.ui.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import dianmobile.eistarandroid.ByhhAndroidApplication;
import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.BoardItemEntity;
import dianmobile.eistarandroid.network.request.AddFriendsRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.network.request.RequestFactory;
import dianmobile.eistarandroid.network.request.RequestType;
import dianmobile.eistarandroid.network.request.SubBoardRequest;
import dianmobile.eistarandroid.ui.Adapter.BoardListAdapter;
import dianmobile.eistarandroid.ui.fragments.AllGroupFragment;
import dianmobile.eistarandroid.ui.fragments.BookmarkFragment;
import dianmobile.eistarandroid.ui.fragments.MyActivitiesFragment;
import dianmobile.eistarandroid.ui.fragments.MyArticlesFragment;
import dianmobile.eistarandroid.ui.fragments.MyFriendsFragment;
import dianmobile.eistarandroid.ui.fragments.MyMailsFragment;
import dianmobile.eistarandroid.ui.fragments.SettingFragment;
import dianmobile.eistarandroid.utils.ConstantsData;
import dianmobile.eistarandroid.utils.DataUtils;
import dianmobile.eistarandroid.utils.SettingInfoManager;
import dianmobile.eistarandroid.utils.ToastUtils;
import im.fir.sdk.FIR;

public class MainActivity extends Activity {

    private final String TAG = getClass().getSimpleName();
    private String fragmentState = ConstantsData.EMPTY_STR;
    private AllGroupFragment allGroupFragment = null;
    private BookmarkFragment bookmarkFragment = null;
    private MyActivitiesFragment myActivitiesFragment = null;
    private MyArticlesFragment myArticlesFragment = null;
    private MyFriendsFragment myFriendsFragment = null;
    private MyMailsFragment myMailsFragment = null;
    private SettingFragment settingFragment = null;
    private Fragment currentFragment = null;

    private ImageButton showSlideMenu;
    private TextView titleMainActivity;
    private ImageButton rightButtonMainActivity;
    private AutoCompleteTextView searchInput;

    /*slideMenu 中的用户名和头像*/
    private TextView tvUserName;
    private CircleImageView userHead;

    private boolean isSearching = false;

    private String userName = ConstantsData.GUEST_USER;
    public static SlidingMenu slidingMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().add(this);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        if (new SettingInfoManager(this).isAutoCheckUpdate()) {
            FIR.checkForUpdateInFIR("d4fc1c0102a1ce96c017daeb9e7cc33a", new MyVersionCheckCallBack(this));
        }
        /*从登录获取用户名*/
        Intent intent = getIntent();
        if(intent.hasExtra("userName") && !intent.getStringExtra("userName").isEmpty()) {
            userName = intent.getStringExtra("userName");
        }

        showSlideMenu = (ImageButton)findViewById(R.id.btn_show_slideMenu);
        titleMainActivity = (TextView)findViewById(R.id.tv_title_mainActivity);
        rightButtonMainActivity = (ImageButton)findViewById(R.id.btn_right_button);
        searchInput = (AutoCompleteTextView)findViewById(R.id.edt_search_input);

        initSlidingMenu();

        setTitleButtonListener();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (currentFragment == null) {
            if (bookmarkFragment == null) {
                bookmarkFragment = new BookmarkFragment();
            }
            fragmentState = ConstantsData.MENU_BOOKMARK;
            changeTitle(ConstantsData.TITLE_RIGHT_SEARCH);
            changeFragment(bookmarkFragment);
        }
        Intent intent = getIntent();
        String fragmentType = intent.getStringExtra("type");
        if (fragmentType != null) {
            switch (fragmentType){
                case ConstantsData.MENU_MY_ACTIVITIES:
                    if(myActivitiesFragment == null){
                        myActivitiesFragment = new MyActivitiesFragment();
                    }
                    fragmentState = ConstantsData.MENU_MY_ACTIVITIES;
                    changeTitle(ConstantsData.TITLE_RIGHT_SMS);
                    changeFragment(myActivitiesFragment);
                    break;
                case ConstantsData.MENU_MY_MAILS:
                    if(myMailsFragment == null){
                        myMailsFragment = new MyMailsFragment();
                    }
                    fragmentState = ConstantsData.MENU_MY_MAILS;
                    changeTitle(ConstantsData.TITLE_RIGHT_SEARCH);
                    changeFragment(myMailsFragment);
                    break;
            }
        }
    }
    @Override
    public void onDestroy() {
        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().remove(this);
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public boolean onKeyDown(int key, KeyEvent event) {
        if (key == KeyEvent.KEYCODE_BACK) {
            if (slidingMenu.isMenuShowing()){
                slidingMenu.toggle();
            }else {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("是否退出？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        MainActivity.this.setResult(RESULT_CANCELED);
                        MainActivity.this.finish();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
            return true;
        }
        return super.onKeyDown(key, event);
    }
    protected void initSlidingMenu() {


        slidingMenu = new SlidingMenu(this);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        slidingMenu.setFadeDegree(0.35f);
        slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);     // make ActionBar to move
        slidingMenu.setBehindOffset(223);
        slidingMenu.setMenu(R.layout.slidingmenu);

        tvUserName = (TextView)findViewById(R.id.tv_user_name);
        userHead = (CircleImageView)findViewById(R.id.btn_user_head);
        if(userName.equals(ConstantsData.GUEST_USER)) {
            userHead.setImageResource(R.drawable.default_face);
        } else {
            RequestFactory.makeNetworkImage(userHead, DataUtils.getUserHeadUrlFromName(userName),
                    R.drawable.default_face, 0);

        }
        tvUserName.setText(userName);

        if (userName.equals(ConstantsData.GUEST_USER)) {
            slidingMenu.findViewById(R.id.btn_menu_myActivities).setVisibility(View.GONE);
            slidingMenu.findViewById(R.id.btn_menu_myArticles).setVisibility(View.GONE);
            slidingMenu.findViewById(R.id.btn_menu_myFriends).setVisibility(View.GONE);
            slidingMenu.findViewById(R.id.btn_menu_myMails).setVisibility(View.GONE);
        }
        setMenuClickListener(slidingMenu);
    }

    /**
     * change the fragment
     * @param toShowFragment the fragment to show in mainActivity
     */
    private void changeFragment(Fragment toShowFragment) {
        //TODO add delay when first add
        if (toShowFragment == myMailsFragment) {
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        } else {
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);    //换到新的fragment后就启用全屏监听滑动
        }
        if (currentFragment == null) {
            getFragmentManager()
                    .beginTransaction()
                    .add(R.id.main_layout, toShowFragment)
                    .commit();
            currentFragment = toShowFragment;
        }else if (currentFragment != toShowFragment) {

            if (toShowFragment.isAdded()) {
                getFragmentManager()
                        .beginTransaction()
                        .hide(currentFragment)
                        .show(toShowFragment)
                        .commit();
            } else {
                getFragmentManager()
                        .beginTransaction()
                        .hide(currentFragment)
                        .add(R.id.main_layout, toShowFragment)
                        .commit();

            }
            currentFragment = toShowFragment;
        }
    }

    /**
     * change the title according to fragment
     * @param state: 1 for search; 2 for add; 3 for don't show;
     */
    private void changeTitle(int state) {
        titleMainActivity.setText(fragmentState);
        switch (state) {
            case ConstantsData.TITLE_RIGHT_SEARCH:
                searchInput.setVisibility(View.INVISIBLE);
                titleMainActivity.setVisibility(View.VISIBLE);
//                rightButtonMainActivity.setVisibility(View.VISIBLE);
                rightButtonMainActivity.setBackgroundResource(R.drawable.ic_search);
                break;
            case ConstantsData.TITLE_RIGHT_ADD:
                searchInput.setVisibility(View.INVISIBLE);
                titleMainActivity.setVisibility(View.VISIBLE);
//                rightButtonMainActivity.setVisibility(View.VISIBLE);
                rightButtonMainActivity.setBackgroundResource(R.drawable.ic_add);
                break;
            case ConstantsData.TITLE_NO_RIGHT:
                searchInput.setVisibility(View.INVISIBLE);
                titleMainActivity.setVisibility(View.VISIBLE);
                rightButtonMainActivity.setVisibility(View.INVISIBLE);
                break;
            case ConstantsData.TITLE_RIGHT_SMS:
                searchInput.setVisibility(View.INVISIBLE);
                titleMainActivity.setVisibility(View.VISIBLE);
//                rightButtonMainActivity.setVisibility(View.VISIBLE);
                rightButtonMainActivity.setBackgroundResource(R.drawable.ic_sms_white);
                break;
            case ConstantsData.TITLE_IN_SEARCH:
                rightButtonMainActivity.setBackgroundResource(R.drawable.ic_close);
                titleMainActivity.setVisibility(View.INVISIBLE);
                searchInput.setVisibility(View.VISIBLE);
                isSearching = true;
                break;
            default:
                break;
        }

    }
    /**
     * listen to click on the menu button and showMenuButton
     * @param  menu slideMenu
     */
    private void setMenuClickListener(SlidingMenu menu) {

        final SlidingMenu slidingMenu = menu;

        showSlideMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(slidingMenu.isMenuShowing()) {
                    slidingMenu.showContent();
                } else {
                    slidingMenu.showMenu();
                }
            }
        });

        findViewById(R.id.btn_menu_bookmark).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ( !fragmentState.equals(ConstantsData.MENU_BOOKMARK)){
                    fragmentState = ConstantsData.MENU_BOOKMARK;
                    if (bookmarkFragment == null) {
                        bookmarkFragment = new BookmarkFragment();
                    }
                    changeTitle(ConstantsData.TITLE_RIGHT_SEARCH);
                    changeFragment(bookmarkFragment);

                }
                slidingMenu.showContent();  //hide menu

            }
        });

        findViewById(R.id.btn_menu_allGroups).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ( !fragmentState.equals(ConstantsData.MENU_ALL_GROUP)){
                    fragmentState = ConstantsData.MENU_ALL_GROUP;
                    if (allGroupFragment == null) {
                        allGroupFragment = new AllGroupFragment();
                    }
                    changeTitle(ConstantsData.TITLE_RIGHT_SEARCH);
                    changeFragment(allGroupFragment);
                }
                slidingMenu.showContent();
            }
        });

        findViewById(R.id.btn_menu_myActivities).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ( !fragmentState.equals(ConstantsData.MENU_MY_ACTIVITIES)){
                    fragmentState = ConstantsData.MENU_MY_ACTIVITIES;
                    if(myActivitiesFragment == null) {
                        myActivitiesFragment = new MyActivitiesFragment();
                    }
                    changeTitle(ConstantsData.TITLE_RIGHT_SMS);
                    changeFragment(myActivitiesFragment);

                }
                slidingMenu.showContent();
            }
        });

        findViewById(R.id.btn_menu_myArticles).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ( !fragmentState.equals(ConstantsData.MENU_MY_ARTICLE)){
                    fragmentState = ConstantsData.MENU_MY_ARTICLE;
                    if(myArticlesFragment == null) {
                        myArticlesFragment = new MyArticlesFragment();
                    }
                    changeTitle(ConstantsData.TITLE_RIGHT_SEARCH);
                    changeFragment(myArticlesFragment);

                }
                slidingMenu.showContent();
            }
        });

        findViewById(R.id.btn_menu_myMails).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ( !fragmentState.equals(ConstantsData.MENU_MY_MAILS)){
                    fragmentState = ConstantsData.MENU_MY_MAILS;
                    if (myMailsFragment == null) {
                        myMailsFragment = new MyMailsFragment();
                    }
                    changeTitle(ConstantsData.TITLE_RIGHT_SEARCH);
                    changeFragment(myMailsFragment);

                }
                slidingMenu.showContent();
            }
        });

        findViewById(R.id.btn_menu_myFriends).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ( !fragmentState.equals(ConstantsData.MENU_MY_FRIENDS)){
                    fragmentState = ConstantsData.MENU_MY_FRIENDS;
                    if (myFriendsFragment == null) {
                        myFriendsFragment = new MyFriendsFragment();
                    }
                    changeTitle(ConstantsData.TITLE_RIGHT_ADD);
                    changeFragment(myFriendsFragment);

                }
                slidingMenu.showContent();
            }
        });

        findViewById(R.id.btn_menu_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ( !fragmentState.equals(ConstantsData.MENU_SETTING)){
                    fragmentState = ConstantsData.MENU_SETTING;
                    if (settingFragment == null ) {
                        settingFragment = new SettingFragment();
                    }
                    changeTitle(ConstantsData.TITLE_NO_RIGHT);
                    changeFragment(settingFragment);

                }
                slidingMenu.showContent();
            }
        });

        findViewById(R.id.btn_user_head).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, UserInfoActivity.class);
                intent.putExtra(ConstantsData.EXTRA_USER_NAME, userName);
                startActivity(intent);
            }
        });
    }

    private void setTitleButtonListener() {
        rightButtonMainActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSearching) {
                    searchInput.setVisibility(View.INVISIBLE);
                    titleMainActivity.setVisibility(View.VISIBLE);
                    rightButtonMainActivity.setBackgroundResource(R.drawable.ic_search);
                    isSearching = false;
                } else if (currentFragment == bookmarkFragment) {
                    searchArticle();
                } else if (currentFragment == allGroupFragment) {
                    searchBoard();
                } else if (currentFragment == myActivitiesFragment) {
                    Log.d(TAG, "我的动态");
                } else if (currentFragment == myArticlesFragment) {
                    searchMyArticle();
                } else if (currentFragment == myMailsFragment) {
                    searchMyMail();
                } else if (currentFragment == myFriendsFragment) {
                    addFriend();
                }
            }
        });
    }

    /**
     * 查找帖子
     * 加上版面名可以复用
     */
    private void searchArticle() {
        changeTitle(ConstantsData.TITLE_IN_SEARCH);
    }

    /**
     * 查找版面
     */
    private void searchBoard() {
        changeTitle(ConstantsData.TITLE_IN_SEARCH);
        final String[] strings = {"asd", "dfs", "asqer", "adqwe"};
//        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, strings);
        final List<BoardItemEntity> allBoardList = new ArrayList<>();
        //TODO 获取所有的版面名
        SubBoardRequest.execute(this, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                if(error != null){
                    ToastUtils.toastNetworkNotWorking(MainActivity.this);
                }else{
                    allBoardList.addAll((List<BoardItemEntity>)result.get("result_data"));
                }
            }
        }, ConstantsData.GROUP_EISTAR);
        BoardListAdapter adapter = new BoardListAdapter(this, allBoardList);
        searchInput.setAdapter(adapter);
        searchInput.setThreshold(1);
        searchInput.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                searchInput.setText(strings[i]);
                Toast.makeText(MainActivity.this, "select on: " + strings[i], Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 查找我的文章
     */
    private void searchMyArticle() {
        changeTitle(ConstantsData.TITLE_IN_SEARCH);
    }

    /**
     * 查找我的信件
     */
    private void searchMyMail() {
        changeTitle(ConstantsData.TITLE_IN_SEARCH);
    }

    /**
     * 添加好友
     */
    private void addFriend() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_add_friends, (ViewGroup)findViewById(R.id.dialog_add_friends));
        new AlertDialog.Builder(this)
                .setTitle("输入用户信息")
                .setView(layout)
                .setNegativeButton("取消", null)
                .setPositiveButton("添加", new AddFriendsListener(layout))
                .show();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    class AddFriendsListener implements DialogInterface.OnClickListener {
        View layout;
        AddFriendsListener(View layout){
            this.layout = layout;
        }
        @Override
        public void onClick(final DialogInterface dialogInterface, int i) {
            EditText edtUserId = (EditText)layout.findViewById(R.id.edt_userid);
            EditText edtRemark = (EditText)layout.findViewById(R.id.edt_remark);
            String userId = edtUserId.getText().toString();
            String remark = edtRemark.getText().toString();
            Map<String, String> params = new HashMap<>();
            params.put("userid", userId);
            params.put("exp", remark);
            params.put("xml", "1");
            AddFriendsRequest.execute(MainActivity.this, RequestType.ADD_FRIENDS, params, new RequestCallback() {
                @Override
                public void onResult(Map<String, Object> result, String error) {
                    if(error != null) {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    } else {
                        if(result.containsKey(ConstantsData.ERROR_RESULT)) {
                            Toast.makeText(MainActivity.this, (String)result.get(ConstantsData.ERROR_RESULT), Toast.LENGTH_SHORT).show();
                        } else {
                            myFriendsFragment.getFriendsData();
                        }
                    }
                    dialogInterface.dismiss();
                }
            });
        }
    }


}
